package com.lisa.auto.service.c3.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.lisa.auto.entity.C3ExportLog;
import com.lisa.auto.entity.c3.model.CarModel;
import com.lisa.auto.entity.c3.model.CarSeries;
import com.lisa.auto.enums.C3UrlEnum;
import com.lisa.auto.mapper.c3.C3CarModelMapper;
import com.lisa.auto.service.C3ExportLogService;
import com.lisa.auto.service.c3.C3CarModelService;
import com.lisa.auto.service.c3.CarSeriesService;
import com.lisa.auto.util.basic.BaseException;
import com.lisa.auto.util.basic.BaseResponse;
import demo.C3ApiDemo;
import demo.request.ModelListRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 车型管理 服务实现类
 * </p>
 *
 * @author suohao
 * @since 2019-12-23
 */
@Service
public class C3CarModelServiceImpl extends ServiceImpl<C3CarModelMapper, CarModel> implements C3CarModelService {

    @Value("${c3.url}")
    private String c3url;
    @Value("${c3.appKey}")
    private String appKey;
    @Value("${c3.secretKey}")
    private String secretKey;

    @Autowired
    private C3ExportLogService exportLogService;
    @Autowired
    private CarSeriesService carSeriesService;

    @Override
    public void addModel(CarModel carModel) {
        if (StringUtils.isEmpty(carModel.getNo())) {
            throw new BaseException("车型编码不能为空");
        }
        if (StringUtils.isEmpty(carModel.getSeriesNo())) {
            throw new BaseException("车系编码不能为空");
        }
        if (StringUtils.isEmpty(carModel.getSeriesName())) {
            throw new BaseException("车系名称不能为空");
        }
        //查询该车架号是否已存在，存在就更新，不存在就新增
        EntityWrapper<CarModel> ew = new EntityWrapper<>();
        ew.eq("no", carModel.getNo());
        List<CarModel> carModels = baseMapper.selectList(ew);
        if (carModels != null && !carModels.isEmpty()) {
            baseMapper.update(carModel, ew);
        } else {
            baseMapper.insert(carModel);
        }

    }

    @Override
    public void modelUpdate(CarSeries carSeries) {
        if (carSeries == null || StringUtils.isEmpty(carSeries.getNo())) throw new BaseException("车系编码为空");
        EntityWrapper<CarSeries> seriesEW = new EntityWrapper<>();
        seriesEW.eq("no", carSeries.getNo());
        List<CarSeries> seriesList = carSeriesService.selectList(seriesEW);
        if (seriesList == null || seriesList.size() < 1) throw new BaseException("未找到对应车系");
        List<CarModel> models = carSeries.getModels();
        if (models != null && !models.isEmpty()) {
            for (CarModel carModel : models) {
                carModel.setSeriesNo(carSeries.getNo());
                carModel.setSeriesName(carSeries.getName());
                EntityWrapper<CarModel> modelEW = new EntityWrapper<>();
                modelEW.eq("no", carModel.getNo());
                modelEW.eq("series_no", carSeries.getNo());
                List<CarModel> modelList = baseMapper.selectList(modelEW);
                //判断该车型是否存在，不存在则新增，存在就更新
                if (modelList == null || modelList.size() < 1) {
                    baseMapper.insert(carModel);
                } else {
                    baseMapper.update(carModel, modelEW);
                }
            }
        }
    }

    @Override
    public List<CarModel> getModelsList(Map<String, Object> condition) {
        EntityWrapper<CarModel> ew = buildWrapper(condition);
        List<CarModel> modelsList = baseMapper.selectList(ew);
        return modelsList;
    }

    @Override
    public Page<CarModel> getModelsListPage(Page<CarModel> page) {
        if (page == null) {
            throw new BaseException("参数不能为空");
        }
        Map<String, Object> condition = page.getCondition();
        EntityWrapper<CarModel> ew = buildWrapper(condition);
        List<CarModel> modelsList = baseMapper.getModelsListPage(ew, page);
        page.setRecords(modelsList);
        return page;
    }

    private EntityWrapper<CarModel> buildWrapper(Map<String, Object> condition) {
        EntityWrapper<CarModel> ew = new EntityWrapper();
        if (condition.get("no") != null && !"".equals(condition.get("no"))) {
            ew.like("no", condition.get("no").toString());
        }
        if (condition.get("name") != null && !"".equals(condition.get("name"))) {
            ew.like("name", condition.get("name").toString());
        }
        if (condition.get("seriesNo") != null && !"".equals(condition.get("seriesNo"))) {
            ew.like("series_no", condition.get("seriesNo").toString());
        }
        if (condition.get("seriesName") != null && !"".equals(condition.get("seriesName"))) {
            ew.like("series_name", condition.get("seriesName").toString());
        }
        if (condition.get("status") != null && !"".equals(condition.get("status"))) {
            ew.eq("status", condition.get("status").toString());
        }
        if (condition.get("startDate") != null && !"".equals(condition.get("startDate"))) {
            ew.ge("gmt_create", condition.get("startDate"));
        }
        if (condition.get("endDate") != null && !"".equals(condition.get("endDate"))) {
            ew.le("gmt_create", condition.get("endDate"));
        }
        return ew;
    }

    @Override
    public void updateCarModel(CarModel carModel) {
        EntityWrapper<CarModel> ew = new EntityWrapper();
        ew.eq("no", carModel.getNo());
        carModel.setIsDelete(1);
        baseMapper.update(carModel, ew);
    }

    @Override
    public List<CarModel> queryModelsToSave(String seriesNo) {
        C3ExportLog exportLog = new C3ExportLog();
        List<CarModel> carModes = new ArrayList<>();
        try {
            String url = c3url + C3UrlEnum.MODELSLISTURL.getUrl();
            ModelListRequest request = new ModelListRequest();
            //request.setVin(vin);
            request.setSeriesNo(seriesNo);
            request.setAppKey(appKey);
            String requstJson = JSON.toJSONString(request);
            exportLog.setInterfaceUrl(url);
            exportLog.setExportKey(seriesNo);
            exportLog.setExportType("GET_MODEL");
            exportLog.setTargetSys("C3");
            exportLog.setDataContent(requstJson);
            String result = C3ApiDemo.get(url, requstJson, secretKey);
            if (StringUtils.isNotBlank(result)) {
                BaseResponse<CarModel> baseResponse = JSONObject.parseObject(result, BaseResponse.class);
                //Object parse = JSONObject.parse(result);
                JSONObject jsonObject = JSONObject.parseObject(result);
                if (!"true".equals(jsonObject.get("returnSuccess").toString())) {
                    throw new BaseException("获取车辆信息失败:" + baseResponse.getReturnErrMsg());
                }
                carModes = JSON.parseArray(JSON.toJSONString(jsonObject.get("list")), CarModel.class);
                //List<CarModel> list = baseResponse.getList();
                exportLog.setExportStatus("1");
                exportLog.setExportResponse(result);
                for (CarModel carMode : carModes) {
                    addModel(carMode);
                }
                // CarModel carModel = list.get(0);
                //baseMapper.update(baseResponse.getData(),ew);
            }
        } catch (Exception e) {
            exportLog.setExportStatus("0");
            exportLog.setExportResponse(e.getMessage());
        }
        exportLogService.insert(exportLog);
        return carModes;
    }

    @Override
    public List<CarModel> getAllCarModel() {
        return baseMapper.getAllCarModel();
    }
    @Override
    public void forbiddenByIds(String ids) {
        if (StringUtils.isEmpty(ids)) throw new BaseException("参数为空");
        String[] split = ids.split(",");
        EntityWrapper<CarModel> ew = new EntityWrapper<>();
        ew.in("id", split);
        List<CarModel> carModels = baseMapper.selectList(ew);
        if (carModels == null || carModels.size() < 1) throw new BaseException("未查询到对应车型信息");
        for (CarModel carModel : carModels) {
            if ("50".equals(carModel.getStatus())) throw new BaseException("存在已删除车型");
            if ("40".equals(carModel.getStatus())) throw new BaseException("存在已禁用车型");
        }
        CarModel info = new CarModel();
        info.setStatus("40");
        info.setGmtModified(new Date());
        baseMapper.update(info, ew);
    }

    @Override
    public void enableByIds(String ids) {
        if (StringUtils.isEmpty(ids)) throw new BaseException("参数为空");
        String[] split = ids.split(",");
        EntityWrapper<CarModel> ew = new EntityWrapper<>();
        ew.in("id", split);
        List<CarModel> carModels = baseMapper.selectList(ew);
        if (carModels == null || carModels.size() < 1) throw new BaseException("未查询到对应车型信息");
        for (CarModel carModel : carModels) {
            if ("50".equals(carModel.getStatus())) throw new BaseException("存在已删除车型");
            if ("10".equals(carModel.getStatus())) throw new BaseException("存在已启用车型");
        }
        CarModel info = new CarModel();
        info.setStatus("10");
        info.setGmtModified(new Date());
        baseMapper.update(info, ew);
    }

    @Override
    public void deleteByIds(String ids) {
        if (StringUtils.isEmpty(ids)) throw new BaseException("参数为空");
        String[] split = ids.split(",");
        EntityWrapper<CarModel> ew = new EntityWrapper<>();
        ew.in("id", split);
        List<CarModel> carModels = baseMapper.selectList(ew);
        if (carModels == null || carModels.size() < 1) throw new BaseException("未查询到对应车型信息");
        for (CarModel carModel : carModels) {
            if ("50".equals(carModel.getStatus())) throw new BaseException("存在已删除车型");
        }
        CarModel info = new CarModel();
        info.setStatus("50");
        info.setGmtModified(new Date());
        baseMapper.update(info, ew);
    }

}
